<!-- 企业登录 -->
<template>
  <div class="login">
    <div class="main">
      <page-head class="header_login" />
      <div class="main-inner">
        <div class="left-text-container">
          <div class="left-text">
            <p>国考云</p>
            <p>在线考试新选择</p>
            <div><span @click="gotoMainPage">了解详情 ></span></div>
          </div>
        </div>
        <div class="bd-container">
          <div class="bd">
            <div class="inner">
              <div class="title">企业管理员登录</div>
              <div class="mode">
                <el-button
                  :class="[mode === 'pwd' ? 'selected' : '']"
                  @click="() => handleSelectMode('pwd')"
                >密码登录</el-button>
                <el-button
                  :class="[mode === 'sms' ? 'selected' : '']"
                  @click="() => handleSelectMode('sms')"
                >验证码登录</el-button>
              </div>
              <div v-show="mode === 'pwd'">
                <el-form
                  ref="form"
                  :model="form"
                  :rules="rules"
                >
                  <el-form-item
                    prop="mobile"
                  >
                    <el-input
                      ref="mobile"
                      v-model="form.mobile"
                      placeholder="请输入手机号"
                      maxlength="11"
                      :validate-event="false"
                      @input.native="() => { form.mobile = form.mobile.replace(/[^\d.]/g, '') }"
                    />
                  </el-form-item>
                  <el-form-item
                    prop="pwd"
                  >
                    <el-input
                      ref="pwd"
                      v-model.trim="form.pwd"
                      placeholder="请输入密码"
                      show-password
                      :validate-event="false"
                    />
                  </el-form-item>
                  <el-form-item>
                    <div
                      v-if="mode === 'pwd'"
                      id="sc"
                      class="verification"
                    />
                  </el-form-item>
                  <el-form-item>
                    <el-button
                      type="primary"
                      class="submit"
                      @click="handleLogin"
                    >登录</el-button>
                  </el-form-item>
                </el-form>
              </div>
              <div v-show="mode === 'sms'">
                <el-form
                  ref="smsForm"
                  :model="smsForm"
                  :rules="smsRules"
                >
                  <el-form-item
                    prop="mobile"
                  >
                    <el-input
                      v-model="smsForm.mobile"
                      placeholder="请输入手机号"
                      maxlength="11"
                      :validate-event="false"
                      @input.native="() => { smsForm.mobile = smsForm.mobile.replace(/[^\d.]/g, '') }"
                    />
                  </el-form-item>
                  <el-form
                    ref="smsForm2"
                    :model="smsForm2"
                    :rules="smsRules2"
                  >
                    <el-form-item
                      class="imgCode"
                      prop="imgCode"
                    >
                      <el-input
                        v-model="smsForm2.imgCode"
                        maxlength="4"
                        placeholder="图片验证码"
                        :validate-event="false"
                      >
                        <img slot="append" class="imageCode" width="90px" height="30px" :src="Vcode.imageCode" @click="getValidateCode">
                      </el-input>
                    </el-form-item>
                  </el-form>
                  <!-- <el-form-item
                    class="imgCode"
                    prop="imgCode"
                  >
                    <el-input
                      v-model="smsForm.imgCode"
                      maxlength="4"
                      placeholder="图片验证码"
                      :validate-event="false"
                    >
                      <img slot="append" class="imageCode" width="90px" height="30px" :src="Vcode.imageCode" @click="getValidateCode">
                    </el-input>
                  </el-form-item> -->
                  <el-form-item
                    prop="smsCode"
                  >
                    <el-input
                      v-model="smsForm.smsCode"
                      placeholder="短信验证码"
                      maxlength="4"
                      :validate-event="false"
                      @input.native="() => { smsForm.smsCode = smsForm.smsCode.replace(/[^\d.]/g, '') }"
                    >
                      <el-button
                        slot="suffix"
                        type="text"
                        class="send-sms"
                        :disabled="isDisabledSendSMS"
                        @click="handleSendSMS"
                      >{{ isDisabledSendSMS ? '验证码（' + remainTime + 'S）' : '发送验证码' }}</el-button>
                    </el-input>
                  </el-form-item>
                  <el-form-item>
                    <div
                      v-if="mode === 'sms'"
                      id="sms_sc"
                      class="verification"
                    />
                  </el-form-item>
                  <el-form-item>
                    <el-button
                      type="primary"
                      class="submit"
                      @click="handleSMSLogin"
                    >登录</el-button>
                  </el-form-item>
                </el-form>
              </div>
              <div class="extra">
                <el-link
                  type="primary"
                  :underline="false"
                  @click.native="$router.push({path:'/register'})"
                >
                  企业注册
                </el-link>
                <el-link
                  type="info"
                  :underline="false"
                  @click="$router.push({path: '/resetPwd'})"
                >
                  忘记密码？
                </el-link>
              </div>
            </div>
          </div>
        </div>
      </div>
      <page-footer />
    </div>
  </div>
</template>

<script>

import { sendLoginSMS, getValidateCode } from '@/api/user'
import PageHead from '@/components/Register/Head_new.vue'
import PageFooter from '@/components/Register/footer'

let intervalId = 0

export default {
  name: 'Login',

  components: {
    PageHead,
    PageFooter
  },

  data() {
    var checkMobile = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入手机号码！'))
      }
      if (value.length !== 11) {
        return callback(new Error('请输入11位手机号码！'))
      } else if (+value[0] !== 1) {
        return callback(new Error('请输入正确的手机号码！'))
      } else {
        callback()
      }
    }
    return {
      mode: 'pwd',

      form: {
        mobile: '',
        pwd: '',
        token: '',
        sig: '',
        sessionId: '',
        smsCode: null
      },

      rules: {
        mobile: [
          {
            required: true,
            validator: checkMobile
          }
        ],
        pwd: [
          {
            required: true,
            message: '请输入密码！'
          }
        ]
      },

      smsForm: {
        mobile: '',
        smsCode: '',
        sig: '',
        sessionId: '',
        token: '',
        imgCode: ''
      },

      smsRules: {
        mobile: [
          {
            required: true,
            validator: checkMobile
          }
        ],
        smsCode: [
          {
            required: true,
            message: '请输入短信验证码！'
          }
        ]
      },

      smsForm2: {
        imgCode: ''
      },

      smsRules2: {
        imgCode: [
          {
            required: true,
            message: '请输入图片验证码！'
          }
        ]
      },

      Vcode: {
        imageCode: '',
        key: ''
      },

      redirect: undefined,

      otherQuery: {},

      remainTimer: '',

      remainTime: 60,

      isDisabledSendSMS: false
    }
  },

  watch: {
    $route: {
      handler(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },

  mounted() {
    // if (this.form.mobile === '') {
    // this.$refs.mobile.focus()
    // } else if (this.form.pwd === '') {
    // this.$refs.pwd.focus()
    // }
    this.initSC()
  },

  methods: {
    handleSelectMode(mode) {
      if (this.mode === mode) {
        return false
      }
      this.mode = mode
      if (mode === 'sms') {
        this.getValidateCode()
        this.smsForm.mobile = this.form.mobile
      } else {
        this.form.mobile = this.smsForm.mobile
      }
      this.$nextTick(() => {
        this.initSC()
      })
    },

    initSC() {
      window.AWSC.use('ic', (state, module) => {
        // 初始化
        window.ic = module.init({
          // 应用类型标识。它和使用场景标识（scene字段）一起决定了智能验证的业务场景与后端对应使用的策略模型。您可以在阿里云验证码控制台的配置管理页签找到对应的appkey字段值，请务必正确填写。
          appkey: 'FFFF0N00000000007E80',
          // appkey: 'FFFF0N00000000007E80',
          // 使用场景标识。它和应用类型标识（appkey字段）一起决定了智能验证的业务场景与后端对应使用的策略模型。您可以在阿里云验证码控制台的配置管理页签找到对应的scene值，请务必正确填写。
          scene: 'ic_login',
          // 声明智能验证需要渲染的目标元素ID。
          renderTo: this.mode === 'sms' ? 'sms_sc' : 'sc',
          // 验证通过时会触发该回调参数。您可以在该回调参数中将会话ID（sessionId）、签名串（sig）、请求唯一标识（token）字段记录下来，随业务请求一同发送至您的服务端调用验签。
          success: (data) => {
            if (this.mode === 'sms') {
              this.smsForm.sessionId = data.sessionId
              this.smsForm.token = data.token
              this.smsForm.sig = data.sig
            } else {
              this.form.sessionId = data.sessionId
              this.form.token = data.token
              this.form.sig = data.sig
            }
          },
          // 验证失败时触发该回调参数
          fail: (failCode) => {
            this.$message({
              message: '验证失败！请重试！' + failCode,
              type: 'error'
            })
          },
          // 验证码加载异常时触发该回调参数
          error: (errorCode) => {
            this.$message({
              message: '验证失败！请重试！' + errorCode,
              type: 'error'
            })
          }
        })
      })
    },

    getValidateCode() {
      getValidateCode().then(res => {
        this.Vcode = res.data
      })
    },

    handleLogin() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const {
            sessionId,
            sig,
            token
          } = this.form

          if (!sessionId || !sig || !token) {
            this.$message.error('请先点击智能验证，完成验证！')

            return
          }
          this.$store.dispatch(
            'user/login',
            this.form
          ).then(() => {
            this.$router.push({
              path: this.redirect || '/',
              query: this.otherQuery
            })
          })
        } else {
          return false
        }
        window.ic.reset()
      })
    },

    handleSendSMS() {
      this.$refs.smsForm2.validate((valid) => {
        this.$refs.smsForm.validateField(['mobile'], errMsg => {
          if (errMsg === '' && valid) {
            this.smsForm.imgCode = this.smsForm2.imgCode
            this.isDisabledSendSMS = true
            this.remainTimer = setInterval(() => {
              if (+this.remainTime === 0) {
                this.isDisabledSendSMS = false
                clearInterval(this.remainTimer)
                this.remainTime = 60
              } else {
                this.remainTime--
              }
            }, 1000)
            this.sendSMS()
          }
        })
      })
    },

    sendSMS() {
      const data = {
        imageCode: this.smsForm.imgCode,
        key: this.Vcode.key,
        mobile: this.smsForm.mobile
      }
      sendLoginSMS(data).then(res => {
        if (res.message === 'ok') {
          this.$message({
            type: 'success',
            message: '短信发送成功！请查收！'
          })
        } else {
          this.isDisabledSendSMS = false
          clearInterval(this.remainTimer)
          this.remainTime = 60
        }
      })
    },

    countdown() {
      this.isDisabledSendSMS = true
      this.remainTime = 60

      clearInterval(intervalId)

      intervalId = setInterval(() => {
        this.remainTime--

        if (this.remainTime < 0) {
          this.isDisabledSendSMS = false

          clearInterval(intervalId)
        }
      }, 1000)
    },

    handleSMSLogin() {
      console.log(this.smsForm)
      this.$refs.smsForm.validate(valid => {
        if (valid) {
          const {
            sessionId,
            sig,
            token
          } = this.smsForm

          if (!sig || !token || !sessionId) {
            this.$message.error('请先完成智能验证，点击按钮即可！')

            return
          }
          this.$store.dispatch(
            'user/login',
            this.smsForm
          ).then(() => {
            this.$router.push({
              path: this.redirect || '/',
              query: this.otherQuery
            })
          })
        } else {
          return false
        }
        window.ic.reset()
      })
    },

    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },

    gotoMainPage() {
      window.location.href = 'https://www.iguokao.com'
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';

.login {
  overflow: auto;
  min-height: 750px !important;
  height: 100vh;
  width: 100vw;
  position: relative;
  background: #f7f8fd url(../../assets/register/bg_1.jpg) no-repeat;
  background-size:100% 100%;

  .main {
    width: 100%;
    height: 100%;
    margin: 0 auto;
    position: relative;
    .header_login {
      position: absolute;
      top: 0;
      left: 0;
    }

    .main-inner {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      .left-text-container {
        width: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        .left-text {
          line-height: 60px;
          p {
            letter-spacing: 0.5em;
            font-size: 30px;
          }
          div {
            cursor: pointer;
            letter-spacing: 0.2em;
            color: red;
          }
        }
      }

      .bd-container {
        width: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        .bd {
          box-shadow: 3px 3px 5px #888888;
          border-radius: 7px;
          background: #fff;
          padding: 30px 60px;
          .inner {
            width: 315px;
            margin: 0 auto;

            .success {
              height: 40vh;
            }

            .upload-button {
              display: flex;
              justify-content: center;
              align-items: center;
              .el-button {
                width: 50%;
              }
            }
          }

          .el-form-item {
            white-space: nowrap;

            &:last-child {
              text-align: center;
            }
          }

          .title {
            font-size: 20px;
            font-weight: 300;
            text-align: center;
            padding: 0 0 15px;
            margin-bottom: 20px;
          }

          .mode {
            margin: 20px 0 30px;
            display: flex;
            justify-content: space-between;

            .el-button {
              padding-left: 45px;
              padding-right: 45px;
              border: 1px solid transparent;

              &:hover,
              &:focus {
                background: #fff;
                border: 1px solid $themeColor;
              }
            }

            .selected {
              background: #fff;
              color: $themeColor;
              border: 1px solid $themeColor;
            }
          }

          .verification {

            .dot,
            .el-icon-success {
              display: block;
              width: 10px;
              height: 10px;
              border-radius: 100px;
              background: $themeColor;
              position: absolute;
              left: 20px;
              top: 50%;
              transform: translateY(-50%);
            }

            .el-icon-success {
              background: none;
              color: $themeColor;
              transform: translateY(calc(-50% + -2px));
            }
          }

          .el-button {
            margin-left: 0;
          }

          .submit {
            font-size: 16px;
            width: 100%;
          }

          .extra {
            position: relative;
            text-align: center;

            .el-link {
              &:nth-child(2) {
                position: absolute;
                right: 0;
                font-size: 12px;
              }
            }
          }
        }
      }
    }

  }
}

::v-deep .el-input__count{
  height: 30px;
}

@media screen and (max-width: 1600px) {
  .left-text{
    left: 15% !important;
  }
  .bd{
    right: 15% !important;
  }
}

.feed-block{
  padding: 30px 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  letter-spacing: 0.1em;
  font-size: 20px;
  line-height: 50px;
}

#sc{
  margin: 0 !important;
  display: flex;
  justify-content: center;
  align-items: center;
}

#sms_sc{
  margin: 0 !important;
  display: flex;
  justify-content: center;
  align-items: center;
}

// .imgCode{
//   width: 60%;
// }
.imageCode{
  cursor: pointer;
  vertical-align: middle;
}
::v-deep .el-input__inner{
  color: #333333 !important;
  font-family: verdana !important;
  font-weight: 700;
}

::v-deep .el-input-group__append{
  background: white;
}
</style>
